//
//  DEveryXDaysViewController.swift
//  Drop
//
//  Created by hushaohua on 2018/5/27.
//  Copyright © 2018年 init. All rights reserved.
//

import UIKit

class DEveryXDaysViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.setupCollectionView();
        self.view.backgroundColor = UIColor(white: 0, alpha: 0.2);
        self.addTapToDismissGesture();
        self.view.addSubview(self.okButton);
        self.view.addSubview(self.cancelButton);
    }
    
    func addTapToDismissGesture() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapToDismiss));
        tap.delegate = self;
        self.view.addGestureRecognizer(tap);
    }
    
    override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        let point = touch.location(in: self.collectionView);
        return point.y < 0;
    }
    
    @objc func tapToDismiss() {
        self.dismiss(animated: false, completion: nil);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setupCollectionView() -> Void {
        self.view.addSubview(self.collectionView);
        self.collectionView.register(DEveryXDayCell.self, forCellWithReuseIdentifier: "Cell");
        self.collectionView.dataSource = self;
        self.collectionView.delegate = self;
        if (self.dataModel.currentDays != nil){
            if (self.dataModel.isCurrentWeekdays()){
                self.startWeekDays();
            }else{
                self.startMonthDays();
            }
        }
    }
    
    lazy var weekdaysControl:UISegmentedControl = {
        var control = UISegmentedControl(items: ["工作日", "周末", "所有"]);
        control.backgroundColor = UIColor.white;
        control.frame = CGRect(x: 10, y: 0, width: self.view.bounds.size.width - 80, height: 32);
        control.addTarget(self, action: #selector(weekdaysControlChanged(_:)), for: .valueChanged);
        return control;
    }();
    @objc func  weekdaysControlChanged(_ sender:UISegmentedControl){
        switch sender.selectedSegmentIndex {
        case 0:
            self.dataModel.selectWeekdayItems();
        case 1:
            self.dataModel.selectWeekendItems();
        case 2:
            self.dataModel.selectAllWeekdayItems();
        default:
            return;
        }
        self.collectionView.reloadData();
    }
    
    lazy var cancelButton:UIButton = {
        var button:UIButton = UIButton(frame: CGRect(x:0,y:self.view.bounds.size.height - 80,width:100, height:80));
//        button.backgroundColor = UIColor.lightGray;
        button.setTitle("Cancel", for: .normal);
        button.setTitleColor(UIColor.gray, for: .normal);
        button.addTarget(self, action: #selector(cancelButtonClicked(_:)), for: .touchUpInside);
        return button;
    }();
    
    @objc func cancelButtonClicked(_ sender:UIButton) {
        self.tapToDismiss();
    }
    
    lazy var okButton:UIButton = {
        var button:UIButton = UIButton(frame: CGRect(x:self.view.bounds.size.width - 100,y:self.view.bounds.size.height - 80,width:100, height:80));
//        button.backgroundColor = UIColor.lightGray;
        button.setTitle("OK", for: .normal);
        button.setTitleColor(UIColor.black, for: .normal);
        button.addTarget(self, action: #selector(okButtonClicked(_:)), for: .touchUpInside);
        return button;
    }();
    
    var didGetCalendarDay:((String, DEveryXDaysModel) -> Void)?;
    @objc func okButtonClicked(_ sender:UIButton) {
        if (self.didGetCalendarDay != nil){
            let select = self.dataModel.selectedDetail();
            self.didGetCalendarDay!(select, self.dataModel);
        }
        self.tapToDismiss();
    }
    
    func startWeekDays() {
        self.dataModel.setCurrentWeekDays();
        if (self.isViewLoaded){
            let height = 100 + self.weekDayLayout.itemSize.width + 20;
            self.weekdaysControl.frame.origin.y = self.view.bounds.size.height - height + 8;
            self.collectionView.frame.origin.y = self.view.bounds.size.height - height;
            self.collectionView.frame.size.height = height;
            self.collectionView.collectionViewLayout = self.weekDayLayout;
            self.collectionView.backgroundColor = UIColor.white;
            self.collectionView.reloadData();
            self.layoutOKCancelButton();
            self.view.addSubview(self.weekdaysControl);
        }
    }
    
    func startMonthDays() {
        self.dataModel.setCurrentMonthDays();
        if (self.isViewLoaded){
            let height = 60 + self.monthDayLayout.itemSize.width * 5 + 20;
            self.collectionView.frame.origin.y = self.view.bounds.size.height - height;
            self.collectionView.frame.size.height = height;
            self.collectionView.collectionViewLayout = self.monthDayLayout;
            self.collectionView.backgroundColor = UIColor.rgbColor(241, 241, 241);
            self.collectionView.reloadData();
            self.layoutOKCancelButton();
            weekdaysControl.removeFromSuperview();
        }
    }
    
//    var calendarDayModel:DEveryXDaysModel?;
    lazy var dataModel:DEveryXDaysModel = {
        var model = DEveryXDaysModel();
        return model;
    }();
    
    func layoutOKCancelButton() {
        self.layoutBottomButton(self.cancelButton);
        self.layoutBottomButton(self.okButton);
    }
    func layoutBottomButton(_ button:UIButton){
        button.frame.origin.y = self.collectionView.frame.minY + (self.dataModel.isCurrentWeekdays() ? self.weekdayContentHeight() : self.monthdayContentHeight());
        button.frame.size.height = self.view.bounds.size.height - button.frame.origin.y;
    }
    
    lazy var weekDayLayout:UICollectionViewFlowLayout = {
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout();
        layout.scrollDirection = .vertical;
        layout.minimumInteritemSpacing = 10;
        layout.sectionInset = UIEdgeInsets(top: 50, left: 10, bottom: 10, right: 10);
        let size:CGFloat = (self.view.bounds.width - 80) / 7;
        layout.itemSize = CGSize(width: size, height: size);
        return layout;
    }();
    func weekdayContentHeight() -> CGFloat{
        return 50 + (self.view.bounds.width - 80) / 7 + 10;
    }
    lazy var monthDayLayout:UICollectionViewFlowLayout = {
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout();
        layout.scrollDirection = .vertical;
        layout.minimumInteritemSpacing = 1;
        layout.minimumLineSpacing = 1;
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10);
        let size:CGFloat = (self.view.bounds.width - 20 - 6) / 7;
        layout.itemSize = CGSize(width: size, height: size);
        return layout;
    }();
    func monthdayContentHeight() -> CGFloat{
        var height:CGFloat = 10;
        let contentHeight:CGFloat = (self.view.bounds.width - 20.0 - 6.0) / 7.0 * 5.0;
        height = height + contentHeight;
        height = height + 4.0 + 10.0;
        return height;
    }
    
    lazy var collectionView:UICollectionView = {
        var view:UICollectionView = UICollectionView(frame: CGRect(x:0,y:self.view.bounds.size.height - 160, width:self.view.bounds.width, height:160), collectionViewLayout: self.weekDayLayout);
        view.backgroundColor = UIColor.white;
        view.showsVerticalScrollIndicator = false;
        return view;
    }();
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1;
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataModel.currentDays != nil ? self.dataModel.currentDays!.count : 0;
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:DEveryXDayCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! DEveryXDayCell;
        let item:DEveryXDayItem = self.dataModel.currentDays![indexPath.item];
        cell.textLabel.text = item.title;
        if (self.dataModel.isCurrentWeekdays()){
            cell.useAsWeekday(self.dataModel.isItemSelected(item));
        }else{
            cell.useAsMonthday(self.dataModel.isItemSelected(item));
        }
        return cell;
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let item:DEveryXDayItem = self.dataModel.currentDays![indexPath.item];
        if (self.dataModel.isItemSelected(item)){
            self.dataModel.UnselectItem(item);
        }else{
            self.dataModel.selectItem(item);
        }
        if (self.dataModel.isCurrentWeekdays()){
            self.weekdaysControl.selectedSegmentIndex = -1;
        }
        self.collectionView.reloadData();
    }

}
